//
//  HomeViewController.swift
//  SinaWeiBo
//
//  Created by ZKJ on 2017/5/17.
//  Copyright © 2017年 ZKJ. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeViewController: BaseViewController {
    
    fileprivate lazy var titleBtn : TitleButton = TitleButton()
    fileprivate lazy var zkjPopAni : ZKJPopAnimation = ZKJPopAnimation {[weak self] (presented) in
        self!.titleBtn.isSelected = presented
    }
    fileprivate lazy var statusArray : [StatusViewModel] = [StatusViewModel]()
    fileprivate lazy var homeHintLabel : UILabel = UILabel()
    fileprivate lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 1.没有登录时设置的内容
        visitorView.addRotationAnim()
        if !isLogin {
            return
        }
        
        // 2.设置导航条的内容
        setUpNavigationBar()
        
        // 3.下拉刷新
        setUpHeadRefreshView()
        
        // 4.上拉加载更多
        setUpFooterRefresh()
        
        // 5.设置下拉刷新指示器
        setUpHintLabel()
        
        // 6.监听通知
        setUpNotification()
    }
}

// MARK:- 设置界面UI
extension HomeViewController {
    
    //设置导航条的内容
    fileprivate func setUpNavigationBar() {
        
        // 设置导航条左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: "navigationbar_friendattention")
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: "navigationbar_pop")
        
        // 设置导航条中间的titleView
        titleBtn.setTitle("天牛哥", for: .normal)
        titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(titleBtn:)), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    //布局下拉刷新
    fileprivate func setUpHeadRefreshView() {
        let head = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewStatus))
        head?.setTitle("下拉刷新", for: .idle)
        head?.setTitle("释放更新", for: .pulling)
        head?.setTitle("刷新中...", for: .refreshing)
        tableView.mj_header = head
        tableView.mj_header.beginRefreshing()
    }
    
    //布局上拉加载更多
    fileprivate func setUpFooterRefresh() {
        tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreStatus))
    }
    
    //布局指示器
    fileprivate func setUpHintLabel() {
//        print(navigationController?.navigationBar.subviews as Any)
        let bestView = findBestView()
//        print(bestView)
        
        var y: CGFloat = 0.0
        if #available(iOS 10.0, *) {
            y = 32
            bestView.addSubview(homeHintLabel)
        } else {
            y = 12
            navigationController?.navigationBar.insertSubview(homeHintLabel, belowSubview: bestView)
        }
        
        homeHintLabel.frame = CGRect(x: 0, y: y, width: UIScreen.main.bounds.width, height: 32)
        homeHintLabel.textAlignment = .center
        homeHintLabel.textColor = UIColor.white
        homeHintLabel.backgroundColor = UIColor.orange
        homeHintLabel.font = UIFont.systemFont(ofSize: 15)
        homeHintLabel.isHidden = true
    }
    
    /**
     iOS10之后，导航条最底层为_UIBarBackground: 0x16589070; frame = (0 -20; 320 64)
     iOS10之前，导航条最底层为_UINavigationBarBackground: 0x13ceac010; frame = (0 -20; 375 64)
     此方法为找到最佳的View，然后再把指示器添加到此view上。
     */
    fileprivate func findBestView() -> UIView {
        //iOS10之前为 _UINavigationBarBackground, iOS10为 _UIBarBackground
        //_UINavigationBarBackground实际为UIImageView子类，而_UIBarBackground是UIView子类
        //之前setBackgroundImage直接赋值给_UINavigationBarBackground，现在则是设置后为_UIBarBackground增加一个UIImageView子控件方式去呈现图片
        
        if #available(iOS 10.0, *) {
            var barBGView: UIView = UIView()
            let targetName = "_UIBarBackground"
            let _UIBarBackgroundClass = NSClassFromString(targetName) as! NSObject.Type
            
            for subView in (navigationController?.navigationBar.subviews)! {
                if subView.isKind(of: _UIBarBackgroundClass) {
                    barBGView = subView
                    break
                }
            }
            return barBGView
        } else {
            var navBarBGView: UIView = UIView()
            let targetName = "_UINavigationBarBackground"
            let _UINavigationBarBackgroundClass = NSClassFromString(targetName) as! NSObject.Type
            
            for subView in (navigationController?.navigationBar.subviews)! {
                if subView.isKind(of: _UINavigationBarBackgroundClass) {
                    navBarBGView = subView
                    break
                }
            }
            return navBarBGView
        }
    }
    
    fileprivate func setUpNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.showPhotos(note:)), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil)
    }
}

// MARK:- 添加事件监听函数
extension HomeViewController {
    @objc fileprivate func titleBtnClick(titleBtn: TitleButton) {
        // 1.设置按钮的状态
        titleBtn.isSelected = !titleBtn.isSelected
        
        // 2.创建弹出的控制器
        let popView = PopCoverVC()
        
        // 3.设置控制器的modal样式
        popView.modalPresentationStyle = .custom
        
        // 4.设置转场的代理
        popView.transitioningDelegate = zkjPopAni
        zkjPopAni.popFrame = CGRect(x: 85, y: 52, width: 150, height: 200)
        
        // 5.弹出控制器
        present(popView, animated: true, completion: nil)
    }
    
    @objc fileprivate func showPhotos(note : NSNotification) {
        print(note.userInfo as Any)
        let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! NSIndexPath
        let picUrls = note.userInfo![ShowPhotoBrowserUrlsKey] as! [NSURL]
        let homeCollObjc = note.object as! HomeCollectionView
        let photoBrowserVC = PhotoBrowserController(indexPath: indexPath, picUrls: picUrls)
        photoBrowserVC.modalPresentationStyle = .custom
        photoBrowserVC.transitioningDelegate = photoBrowserAnimator
        
        //设置动画的代理
        photoBrowserAnimator.presentedDelegate = homeCollObjc
        photoBrowserAnimator.indexPath = indexPath
        photoBrowserAnimator.dismissedDelegate = photoBrowserVC
        present(photoBrowserVC, animated: true, completion: nil)
    }
}

extension HomeViewController {
    
    //下拉刷新
    @objc fileprivate func loadNewStatus() {
        requestHomeData(isNew: true)
    }
    
    //上拉加载更多
    @objc fileprivate func loadMoreStatus() {
        requestHomeData(isNew: false)
    }
    
    fileprivate func requestHomeData(isNew : Bool) {
        
        //1.获取since_id
        var sinceid : Int64 = 0
        var max_id : Int64 = 0
        if isNew {
            sinceid = statusArray.first?.status?.mid ?? 0
        } else {
            max_id = statusArray.last?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        print("sinceid : \(sinceid)")
        print("max_id : \(max_id)")
        
        ZkjNetworkTool.shareInstance.requestToHomeTimeLine(since_id: IntMax(sinceid), max_id: IntMax(max_id)) { (result, error) in
            // 1.错误校验
            if error != nil {
                print(error as Any)
                return
            }
            
            // 2.获取可选类型中的数据
            guard let resultArray = result else {
                return
            }
            print(result as Any)
            
            // 3.遍历微博对应的字典
            var tempStatusArr = [StatusViewModel]()
            for statusDic in resultArray {
                let status = StatusModel(dict: statusDic)
                let viewModel = StatusViewModel(status: status)
                tempStatusArr.append(viewModel)
            }
            
            // 4.将数据放入到成员变量的数组中
            if isNew {
                let tempFirstMid = tempStatusArr.first?.status?.mid
                let currentFirstMid = self.statusArray.first?.status?.mid
                if tempFirstMid != currentFirstMid {
                    self.statusArray = tempStatusArr + self.statusArray
                }
            } else {
                self.statusArray += tempStatusArr
            }
            
            // 5.缓存图片
            self.cacheImages(viewModels: tempStatusArr)
        }
    }
    
    fileprivate func cacheImages(viewModels : [StatusViewModel]) {
        //1.创建group
        let group = DispatchGroup()
        
        //2.缓存图片
        for viewModel in viewModels {
            for picUrl in viewModel.picUrls {
                group.enter()
                SDWebImageManager.shared().loadImage(with: picUrl, options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                    print("下载一张图片")
                    group.leave()
                })
            }
        }
        
        //3.刷新表格
        group.notify(queue: DispatchQueue.main) { 
            print("刷新表格")
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            self.homeHintLabelAnimation(count: viewModels.count)
        }
    }
    
    //首页显示提示的label
    fileprivate func homeHintLabelAnimation(count : Int) {
        self.homeHintLabel.isHidden = false
        self.homeHintLabel.text = count == 0 ? "没有最新微博" : "新增\(count)条微博"
        UIView.animate(withDuration: 1.0) {
            if #available(iOS 10.0, *) {
                self.homeHintLabel.frame.origin.y = 64
            } else {
                self.homeHintLabel.frame.origin.y = 44
            }
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: {
                if #available(iOS 10.0, *) {
                    self.homeHintLabel.frame.origin.y = 32
                } else {
                    self.homeHintLabel.frame.origin.y = 12
                }
            }, completion: { (_) in
                self.homeHintLabel.isHidden = true
            })
        }
    }
}

// MARK:- tableView的数据源方法和代理方法
extension HomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "home") as! HomeCell
        cell.viewModel = statusArray[indexPath.row]
        return cell
    }
    
    override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let viewModel = statusArray[indexPath.row]
        return viewModel.cellHeight
    }
}



